package beer.coder.walawala.persist;

import beer.coder.walawala.common.config.ApplicationConfigure;
import beer.coder.walawala.common.constant.Constant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 保存应用配置信息.
 *
 * @author amath0312
 * @version 1.0
 * @date 2019-10-24 21:15
 */
public class ConfigureWriter {

  protected File file;

  public ConfigureWriter(String file) {
    this.file = new File(file);
  }

  public ConfigureWriter(File file) {
    this.file = file;
  }

  public ConfigureWriter() {

  }

  /**
   * 将应用配置保存到json中.下次启动时，应用将从配置文件中加载配置信息.
   *
   * @param configure 应用配置信息
   *
   * @throws IOException 文件写入异常
   */
  public void save(ApplicationConfigure configure) throws IOException {
    if (file == null) {
      throw new IllegalArgumentException("配置文件保存路径不能为空");
    }
    if (configure == null) {
      throw new IllegalArgumentException("ApplicationConfigure不能为空(null)");
    }

    if (file.getParentFile() != null && !file.getParentFile().exists()) {
      file.getParentFile().mkdirs();
    }
    ConfigureUtil.fillDefaultValues(configure);

    try (FileOutputStream writer = new FileOutputStream(file)) {
      JSON.writeJSONString(writer, Constant.ENCODING, configure, SerializerFeature.PrettyFormat);
    }
  }


  public File getFile() {
    return file;
  }

  public void setFile(File file) {
    this.file = file;
  }
}
